import { axios, api } from '../Axios/index.js';
import { Loading } from 'element-ui';
import _ from 'lodash';
let isDev = process.env.NODE_ENV == 'development';

let funFormat = {
  resourceChannels: data => {
    if (data.length <= 0) {
      return [];
    }
    return data.map(v => {
      return {
        label: v.remark,
        value: v.fromSource_Id,
        FSTID: v.fromSource_Type_Id, //外部联系人渠道，可能有用，备用
        CDID: v.company_Department_Id, //归属分公司id，可能有用，备用
      };
    });
  },
  workbench: data => {
    if (data.length <= 0) {
      return [];
    }
    return data.map((v, i) => {
      return {
        label: v.companyName,
        value: v.eS_Company_Id,
        isHidden: _.get(v, 'isHidden', false),
        isDefault: _.get(v, 'isDefault', false),
      };
    });
  },
  crmProduct: data => {
    if (data.length <= 0) {
      return [];
    }
    let arr = data.map(v => {
      let beLongTo = v.customer_Order_Type_Ids
        .split(',')
        .map(v => {
          return parseInt(v);
        })
        .filter(v => {
          return v != 0;
        });
      return {
        label: v.productName,
        value: v.productId,
        money: v.productMoney,
        beLongTo: beLongTo,
        item: v,
      };
    });
    if (isDev) {
      let err = arr.reduce((t, v, i, a) => {
        a.forEach(item => {
          if (item.label == v.label && item.value != v.value) {
            t.push(`[${v.value}]和[${item.value}]有相同的【${v.label}】`);
          }
        });
        return t;
      }, []);
      if (err.lengt > 0) {
        console.log(err);
      } else {
        console.log(`未发现异常`);
      }
    } //这里是怀疑数据唯一性后的自检程序，非开发环境不会调用
    return arr;
  },
  payType: data => {
    if (data.length <= 0) {
      return [];
    }
    return data.map(v => {
      return {
        key: v.customer_Order_Pay_Type_Id,
        label: v.remark,
        value: v.customer_Order_Pay_Type_Id,
      };
    });
  },
  department: data => {
    if (data.length <= 0) {
      return [];
    }
    function convertTree(tree, opt) {
      let def = {
        keyChild: 'children',
        sKeyChild: 'children',
        keyLabel: 'label',
        sKeyLabel: 'label',
        keyValue: 'value',
        sKeyValue: 'value',
      };
      let opts = Object.assign(def, opt);
      if (!_.isArray(tree)) return;
      return tree.map(node => {
        let newNode = {};
        newNode[opts.keyLabel] = node[opts.sKeyLabel];
        newNode[opts.keyValue] = node[opts.sKeyValue];
        let child = node[opts.sKeyChild];
        if (child != null) {
          newNode[opts.keyChild] = convertTree(child, opt);
        }

        return newNode;
      });
    }

    let gdata = data.reduce((t, v, i, a) => {
      let item = {
        label: v.department_Name,
        value: v.company_Department_Id,
        children: convertTree(v.nextNode, {
          sKeyChild: 'nextNode',
          sKeyLabel: 'department_Name',
          sKeyValue: 'company_Department_Id',
        }),
      };
      t.push(item);
      return t;
    }, []);
    return gdata;
    return data.map(v => {
      return { label: v.department_Name, value: v.company_Department_Id };
    });
  },
  belongToSales: data => {
    if (data.length <= 0) {
      return [];
    }
    return data.map(v => {
      return {
        key: v.company_Employee_Id,
        label: v.realName,
        value: v.realName,
        pid: v.company_Department_Id,
      };
    });
  },
  rFReportForms: data => {
    if (data.length <= 0) {
      return [];
    }
    return data.map(v => {
      return { label: v.title, value: v.rF_ReportForms_Id };
    });
  },
  theLabel: data => {
    if (data.length <= 0) {
      return [];
    }
    let gdata = data.reduce((t, v, i, a) => {
      let exIdx = t.findIndex(es => {
        return es.value == v.eS_Company_Id;
      });
      if (exIdx < 0) {
        t.push({
          value: v.eS_Company_Id,
          children: [
            {
              value: v.groupId,
              label: v.groupName,
              children: [
                {
                  value: v.tag_id,
                  label: v.name,
                },
              ],
            },
          ],
        });
      } else {
        let gIdx = t[exIdx].children.findIndex(g => {
          return g.value == v.groupId;
        });
        if (gIdx < 0) {
          t[exIdx].children.push({
            value: v.groupId,
            label: v.groupName,
            children: [
              {
                value: v.tag_id,
                label: v.name,
              },
            ],
          });
        } else {
          t[exIdx].children[gIdx].children.push({
            value: v.tag_id,
            label: v.name,
          });
        }
      }
      return t;
    }, []);
    return gdata;
  },
};

export default {
  namespaced: true, // conditional.js
  state: {
    nickname: {
      README: '昵称',
      DEFAULT: '',
      type: 'keyword',
      option: {},
      value: '',
    }, // 昵称
    resourceChannels: {
      README: '资源渠道',
      DEFAULT: [],
      type: 'multiSelect',
      options: [],
      initOption: { label: '全部', value: 0 },
      value: [],
    },
    focusOn: {
      README: '是否关注',
      DEFAULT: '',
      type: 'radio',
      options: [
        { label: '全部', value: '' },
        { label: '是', value: '1' },
        { label: '否', value: '0' },
      ],
      value: 0,
    },
    repeatResources: {
      README: '是否重复资源',
      DEFAULT: '',
      type: 'radio',
      options: [
        { label: '全部', value: '' },
        { label: '是', value: '1' },
        { label: '否', value: '0' },
      ],
      value: 0,
    },
    globalRepeat: {
      README: '是否全局重复',
      DEFAULT: '',
      type: 'radio',
      options: [
        { label: '全部', value: '' },
        { label: '是', value: '1' },
        { label: '否', value: '0' },
      ],
      value: 0,
    },
    flagDelete: {
      README: '是否删除',
      DEFAULT: '',
      type: 'radio',
      options: [
        { label: '全部', value: '' },
        { label: '是', value: '1' },
        { label: '否', value: '0' },
      ],
      value: 0,
    },
    flagDeparture: {
      README: '离职状态',
      DEFAULT: '',
      type: 'radio',
      options: [
        { label: '全部', value: '' },
        { label: '是', value: '1' },
        { label: '否', value: '0' },
      ],
      value: 0,
    },
    workbench: {
      README: '工作台',
      DEFAULT: 0,
      type: 'multiSelect',
      options: [{ label: '全部', value: 0 }],
      initOption: { label: '全部', value: 0 },
      value: [],
    },
    订单类型: {
      README: '订单类型',
      DEFAULT: 0,
      type: 'radio',
      options: [
        { value: 1, label: '新单' },
        { value: 2, label: '续费' },
        { value: 3, label: '复购' },
        { value: 4, label: '变更合同', disabled: true },
        { value: 5, label: '开户', disabled: true },
        { value: 6, label: '升级' },
      ],
      initOption: { label: '全部', value: 0 },
      value: [],
    },
    crmProduct: {
      README: '产品信息',
      DEFAULT: 0,
      type: 'multiSelect',
      options: [{ label: '全部', value: 0 }],
      initOption: { label: '全部', value: 0 },
      value: [],
    },
    payType: {
      README: '支付方式',
      DEFAULT: 0,
      type: 'multiSelect',
      options: [{ label: '全部', value: 0 }],
      initOption: { label: '全部', value: 0 },
      value: [],
    },
    客服企微: {
      README: '客服企微',
      DEFAULT: 0,
      type: 'soloSelect',
      options: [],
      value: [],
    },
    department: {
      README: '归属部门',
      DEFAULT: 0,
      type: 'soloSelect',
      options: [],
      value: [],
    },
    belongToSales: {
      README: '归属销售',
      DEFAULT: 0,
      type: 'multiSelect',
      options: [{ label: '全部', value: 0 }],
      initOption: { label: '全部', value: 0 },
      value: [],
    },
    theLabel: {
      README: '标签',
      DEFAULT: 0,
      type: 'multiSelect',
      options: [{ label: '全部', value: 0 }],
      value: [],
    },
    releaseTime: {
      README: '发布时间',
      DEFAULT: 0,
      type: 'dateTimeRange',
      options: {},
      value: [null, null],
    },
    rFReportForms: {
      README: '资源报表',
      DEFAULT: 0,
      type: 'multiSelect',
      options: [],
      initOption: '',
      value: [],
    },
    joinGroup_State: {
      README: '客户加群情况',
      DEFAULT: '',
      type: 'soloSelect',
      options: [
        { label: '全部', value: '' },
        { label: '未加群', value: 0 },
        { label: '已加群', value: 1 },
        { label: '退群', value: 2 },
      ],
      value: [],
    },
    ArrEmployee: [],
  },
  getters: {
    getValue: function(state) {
      conaole.log(state);
    },
  }, //调用时要用this.$store.getters['molle/getValue']
  mutations: {
    test: function() {
      console.log('test');
    },
    initOptions: function(state, { key, data }) {
      if (!_.has(state, [key, 'options'])) {
        return;
      } //保险
      let tar = state[key].options;
      tar.splice(0, tar.length);
      if (_.has(state, [key, 'initOption'])) {
        tar.push(state[key].initOption);
      } //保险
      let arr = funFormat[key](data);

      arr.forEach((v, i) => {
        tar.push(v);
      });
    },
    initDEFAULT: function(state, { key, data }) {
      if (!_.has(state, [key, 'options'])) {
        return;
      } //保险
      let opts = state[key].options;
      let defValue = opts.find(v => {
        return v.isDefault;
      });
      if (!defValue) {
        console.warn(`key:【${key}】，没有默认值`);
      }
      state[key].DEFAULT = _.get(defValue, 'value', null);
    },
    setEmployeeData: function(state, data) {
      data.forEach(v => {
        state.ArrEmployee.push(v);
      });
    },
  },

  actions: {
    getResourceChannels(ctx, payload) {
      api
        .getResourceChannels(payload)
        .then(res => {
          if (res.data.length > 0) {
            return Promise.resolve(res.data);
          }
        })
        .then(res => {
          ctx.commit('initOptions', { key: 'resourceChannels', arr: res });
        });
    }, // 资源渠道

    getWorkbench(ctx, payload) {
      api
        .getEsCompanyList(payload)
        .then(res => {
          if (res.data.length > 0) {
            return Promise.resolve(res.data);
          }
        })
        .then(res => {
          ctx.commit('initOptions', { key: 'workbench', arr: res });
          return Promise.resolve(res);
        })
        .then(res => {
          ctx.commit('initDEFAULT', { key: 'workbench' });
        });
    }, // 工作台

    getDepartment(ctx, payload) {
      api
        .getCompanyDepartmentList(payload)
        .then(res => {
          if (res.data.length > 0) {
            return Promise.resolve(res.data);
          }
        })
        .then(res => {
          ctx.commit('initOptions', { key: 'department', arr: res });
        });
    }, // 归属部门

    getBelongToSales(ctx, payload) {
      api
        .getCompanyEmployeeList(payload)
        .then(res => {
          if (res.data.length > 0) {
            return Promise.resolve(res.data);
          }
          return Promise.reject();
        })
        .then(res => {
          ctx.commit('initOptions', { key: 'belongToSales', arr: res });
        });
    }, // 归属销售

    getTheLabel(ctx, payload) {
      api
        .getTheLabel()
        .then(res => {
          if (res.data.length > 0) {
            return Promise.resolve(res.data);
          }
        })
        .then(res => {
          ctx.commit('initOptions', { key: 'theLabel', arr: res });
        });
    }, // 标签，还没有看到
  },
};
